package com.fan89.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fan89.common.lang.Result;
import com.fan89.dto.BlogDetailDto;
import com.fan89.entity.Blog;
import com.fan89.entity.User;
import com.fan89.service.BlogService;
import com.fan89.service.TagService;
import com.fan89.service.TypeService;
import com.fan89.service.UserService;
import com.fan89.util.ShiroUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yongbiao.fan
 * @since 2020-06-14
 */
@Api(value = "博客管理api",tags = "博客管理相关接口")
@RestController
public class BlogController {

    @Autowired
    BlogService blogService;
    @Autowired
    TypeService typeService;
    @Autowired
    TagService tagService;
    @Autowired
    UserService userService;

    /**
     * 文章列表
     *
     * @param currentPage
     * @return
     */
    @ApiOperation(value = "博客列表",notes = "博客列表")
    @GetMapping("/blogs")
    public Result list(@RequestParam(defaultValue = "1") Integer currentPage) {

        Page page = new Page(currentPage, 5);
        IPage pageData = blogService.page(page, new QueryWrapper<Blog>().orderByDesc("create_time"));
        List<Blog> blogList = pageData.getRecords();
        List<BlogDetailDto> blogs = new ArrayList<>(blogList.size());
        for (Blog blog : blogList) {
            BlogDetailDto blogDetailDto = new BlogDetailDto();
            BeanUtil.copyProperties(blog, blogDetailDto);
            if (blog.getTypeId() != null) {
                String type = typeService.getById(blog.getTypeId()) != null ? typeService.getById(blog.getTypeId()).getName() : "未知";
                blogDetailDto.setType(type);
            } else {
                blogDetailDto.setType("无分类");
            }
            if (blog.getUserId() != null) {
                String userName = userService.getById(blog.getUserId()) != null ? userService.getById(blog.getUserId()).getNickname() : "未知";
                blogDetailDto.setUsername(userName);
            }
            blogs.add(blogDetailDto);
        }
        pageData.setRecords(blogs);
        return Result.success("成功获取全部文章数据", pageData);
    }

    /**
     * 文章详情
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "博客详情",notes = "博客详情")
    @GetMapping("/blog/{id}")
    public Result detail(@PathVariable(name = "id") Long id) {

        Blog blog = blogService.getById(id);
        Assert.notNull(blog, "本文章已被删除");
        return Result.success("成功读取文章数据", blog);
    }

    /**
     * 文章编辑
     *
     * @param blog
     * @return
     */
    @ApiOperation(value = "博客编辑",notes = "博客编辑")
    @RequiresAuthentication //认证后方可访问该接口
    @PostMapping("/blog/edit")
    public Result edit(@Validated @RequestBody Blog blog) {

        Blog temp = null;
        Long currentUserId = ShiroUtils.getProfile().getId().longValue(); //获取当前用户id
        if (blog.getId() != null) {
            temp = blogService.getById(blog.getId());
            // 只能编辑自己的文章
            Assert.isTrue(temp.getUserId().longValue() == currentUserId, "无编辑权限");
        } else {
            //初始化新文章
            temp = new Blog();
            temp.setUserId(currentUserId);
//            temp.setCreated(LocalDateTime.now());
            temp.setStatus(0);
        }
        //复制文章数据
        BeanUtil.copyProperties(blog, temp, "id", "userId", "create_time", "status");

        blogService.saveOrUpdate(temp);
        return Result.success("成功发表文章");
    }


    /**
     * 文章删除
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "博客删除",notes = "博客删除")
    @RequiresAuthentication
    @GetMapping("/blog/delete/{id}")
    public Result delete(@PathVariable(name = "id") String id) {
//        Long currentUserId = ShiroUtils.getProfile().getId().longValue();
//        if(currentUserId==null&&currentUserId!=1L){
//            return Result.error("抱歉，您没有删除权限");
//        }
        Long currentUserId = ShiroUtils.getProfile().getId().longValue();
        if (currentUserId != null) {
            User user = userService.getById(currentUserId);
            if (!"ROOT".equals(user.getUserType())) {
                return Result.error("您没有权限删除文章");
            }
        } else {
            return Result.error("请先登录");
        }
        boolean result = blogService.removeById(id);// 据库中为Long id
        Assert.isTrue(result, "本文章已被删除");
        return Result.success("成功删除本文章");
    }

    /**
     * 模糊查询
     *
     * @param title
     * @return
     */
    @ApiOperation(value = "博客删除",notes = "博客删除")
    //Error:Failed to convert value of type 'java.lang.String' to required type 'java.lang.Long';
    @GetMapping("/blog/findByTitle")
    public Result findByTitle(@RequestParam(defaultValue = "") String title) {
        List<Blog> blogs = blogService.list(new QueryWrapper<Blog>()
                .like("title", title)
                .orderByDesc("create_time"));
        Assert.notNull(blogs, "未查询到指定文章");
        return Result.success("成功查询到指定文章", blogs);
    }


}
